import { ValidateCredentials } from "~/lib/server";


export async function signin(username: string, password: string) {

    const response = await ValidateCredentials({ "name": username, "password": password });

    if (response.ok) {

        const data = await response.json();
        const expiresAT = new Date(new Date().getTime() + data.expiresIn * 1000);
        // if (typeof window !== 'undefined') {
        localStorage.setItem('idToken', data.idToken);
        localStorage.setItem("expiresAt", expiresAT.toString());
        // }


    } else {
        throw new Error(`HTTP error: Status ${response.status}`);
    }
}

export function isLoggedIn() {

    const expiration = localStorage.getItem("expiresAt") || "";

    const expiresAt = new Date(expiration);
    if (isNaN(expiresAt.getTime())) {
        return false;
    }

    return Date.now() < expiresAt.getTime();


}

export async function signout() {

    localStorage.removeItem("idToken");
    localStorage.removeItem("expiresAt");


}